package com.shiguiwu.springmybatis.spring.aop.beanfactory;

import com.shiguiwu.springmybatis.spring.autowired.C;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.xml.bind.SchemaOutputResolver;
import java.lang.reflect.Method;

/**
 * @description: 测试
 * @author: stone
 * @date: Created by 2021/6/9 17:33
 * @version: 1.0.0
 * @pakeage: com.shiguiwu.springmybatis.spring.aop.beanfactory
 */
//@Configuration
public class BeanFactoryTests {

    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanFactoryTests.class);

        Cattle service1Proxy = context.getBean("factoryBean", Cattle.class);

        service1Proxy.drinkWater();

        service1Proxy.eatGrass();
    }

    @Bean
    public Cattle cattle() {
        return new Cattle();
    }


    @Bean
    public MethodBeforeAdvice beforeAdvice() {
        return new MethodBeforeAdvice() {
            @Override
            public void before(Method method, Object[] objects, Object o) throws Throwable {
                System.out.println("准备调用方法" + method.getName());

            }
        };
    }

    @Bean
    public MethodInterceptor interceptor() {
        return new MethodInterceptor() {
            @Override
            public Object invoke(MethodInvocation invocation) throws Throwable {
                long s = System.nanoTime();
                Object result = invocation.proceed();
                System.out.println("调用方法耗时。。：" + (System.nanoTime() - s));
                return result;
            }
        };
    }


    @Bean
    public ProxyFactoryBean factoryBean() {
        //1.创建
        ProxyFactoryBean bean = new ProxyFactoryBean();
        //2.设置代理
        bean.setTargetName("cattle");
        //3.设置通知
        bean.setInterceptorNames("interceptor", "beforeAdvice");

        return bean;
    }
}
